package com.probiz.estoresa.system.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.navigator.menu.MenuComponent;
import net.sf.navigator.menu.MenuRepository;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.model.system.AppMenu;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.ContextUtil;
import com.probiz.estore.system.service.AppMenuManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class AppMenuController extends GenericStoreAdminController<AppMenu> {
    private AppMenuManager appMenuManager = null;
    private Short belongTo = null;
    public void setBelongTo(Short belongTo) {
		this.belongTo = belongTo;
	}
    public void setAppMenuManager(AppMenuManager inMgr) {
        this.appMenuManager = inMgr;
    }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(AppMenu entity) {
		return entity.getAppMenuName();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = appMenuManager;
	}

	public ModelAndView defaultAction(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView(listView);
		List<AppMenu> menuListRes = appMenuManager.findTopMenus(belongTo,Constants.SECURITY_TYPE_RESOURCE);
		List<AppMenu> menuListMenu = appMenuManager.findTopMenus(belongTo,Constants.SECURITY_TYPE_MENU);
		
		String parentId = request.getParameter("parentId");
		parentId=StringUtils.isBlank(parentId)?"-11":parentId;
		mav.addObject("menuListRes",menuListRes);
		mav.addObject("menuListMenu",menuListMenu);
		mav.addObject("parentId",parentId);
		
		return mav;
	}
	
	public ModelAndView search(HttpServletRequest request,HttpServletResponse response) {
		setDefaultPageSize(20);
		ModelAndView mav = new ModelAndView("system/include/menuListBody");
		SearchCriteria sc = createSearchCriteria(request);
		List results = appMenuManager.searchByCriteria(sc,belongTo);
		mav.addObject("appMenuList", results);
		Integer menuId = RequestUtil.getInteger(request, "parentId",0);
		if(menuId.intValue()>0){
			mav.addObject("appMenu", appMenuManager.getById(menuId));
		}else{
			
		}
		return mav;
	}
	
	/**
	 * 获取树节点，ajax方式
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getTreeItems(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/catalog/include/appMenuTreeAjax");
		String menuId = RequestUtil.getParameterNullSafe(request, "menuId");
		AppMenu parent = appMenuManager.getById(Integer.valueOf(menuId));
		mv.addObject("menuList",parent.getChildren());
		return mv;
		
	}

	/**
	 * 按menuIds的顺序更新目录sortOrder
	 */
	public ModelAndView updateMenusSortOrder(HttpServletRequest request, HttpServletResponse response) {
		Integer[] menuIds = RequestUtil.getIntegerArrayNullSafe(request,"menuIds");
		appMenuManager.updateMenusSortOrder(menuIds);
		return null;
	}

	/**
	 * 按menuId删除目录
	 */
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer menuId = RequestUtil.getInteger(request, "menuId");
		try{
			Map<String, Object> data = appMenuManager.deleteFully(menuId);
			return getModelAndAjaxJsonView(data);
		}catch(Exception e){
			Map<String, Object> returnMsgs = new HashMap<String, Object>();
			returnMsgs.put("result", -1);
			returnMsgs.put("message", getMessage("common.message.delete.constraintViolation")+getMessage("appMenu.del.constraintViolation"));
			return getModelAndAjaxJsonView(returnMsgs);
		}
	}

	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("system/include/menuFormBody");
		Integer entityId = RequestUtil.getInteger(request,"menuId",-11);
		AppMenu entity = entityId.intValue()>0?appMenuManager.getById(entityId):new AppMenu();
		
		if(entity.getMenuId()==null){//新增
			String parentId = request.getParameter("parentId");
			parentId=StringUtils.isBlank(parentId)?"-11":parentId;
			if(!parentId.equals("-11")&&!parentId.equals("-10")){
				entity.setParent(appMenuManager.getById(new Integer(parentId)));
			}
			if(entity.getParent()!=null){
				entity.setType(entity.getParent().getType());
			}else if(parentId.equals("-11")){
				entity.setType(new Short("1"));
			}else{
				entity.setType(new Short("0"));
			}
		}
		mav.addObject("appMenu", entity);
		return mav;
	}

	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) {
		return edit(request, response);
	}

	/**
	 * 前置绑定，避免验证错误
	 * 
	 * @param entity
	 *            实体
	 */
	private void bindReady(AppMenu entity) {
		if (null == entity.getMenuId()) {
            //case:新增
            entity.setSortOrder(AppMenu.SORTORDER_DEFAULT_VALUE);
        }
	}

	/**
	 * 加入返回参数
	 * 
	 * @param data
	 * @param product
	 * @param request
	 */
	private void buildReturnInfo(Map<String, Object> data, AppMenu entity, HttpServletRequest request) {
		data.put("menuId", entity.getMenuId());
		data.put("name", entity.getMenuName());
		data.put("title", entity.getTitle());
		data.put("depth", entity.getDepth());
		data.put("count", entity.getChildren().size());
		data.put("threeLevel", entity.isThreeLevel());
	}

	/**
	 * 将menu-config.xml中的菜单load到数据库中
	 */
	public ModelAndView loadMenus(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String menuConfig = "/WEB-INF/classes/conf/menu-config.xml";
		MenuRepository repository = new MenuRepository();
		repository.setLoadParam(menuConfig);
		repository.setServletContext(request.getSession().getServletContext());
		repository.load();
		//MenuRepository repository = (MenuRepository) request.getSession().getServletContext().getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
		List<MenuComponent> tmenus = repository.getTopMenus();
		int i=1;
		for(MenuComponent mc:tmenus){
			AppMenu menu = tomenu(mc,null,i++);
		}
		
		
//		List<AppMenu> lists = appMenuManager.findByHql("from AppMenu m where m.appMenu !=null order by menuId asc");
//		for(AppMenu m:lists){
//			try{
//				m.setMenuPath(m.getMenuPath_());
//				appMenuManager.save(m);
//			}catch(Exception e){}
//		}
		ContextUtil.getInstance().reloadMenuRepository();
		return defaultAction(request,response);
	}
	
	private AppMenu tomenu(MenuComponent m,AppMenu pm,int sortOrder){
		AppMenu menu = appMenuManager.getAppMenuByMenuName(m.getName());
		if(menu==null){
			menu = new AppMenu();
			menu.setType(Constants.SECURITY_TYPE_MENU);
			menu.setBelongTo(Constants.SECURITY_BELONGTO_ADMIN);
			menu.setMenuName(m.getName());
			menu.setUrl(m.getPage());
			menu.setSortOrder(sortOrder);
			menu.setTitle(m.getTitle());
			try{
				menu.setTitle(getMessage(m.getTitle()));
			}catch(Exception e){
				e.printStackTrace();
			}
			menu.setParent(pm);
			//System.out.println(menu.getMenuName()+"--"+menu.getTitle()+"--"+menu.getUrl());
			appMenuManager.configToDb(menu);
		}else{
//			menu.setUrl(m.getPage());
//			try{
//				menu.setTitle(getMessage(m.getTitle()));
//			}catch(Exception e){}
//			appMenuManager.save(menu);
		}
		if(!m.getComponents().isEmpty()){
			int i=1;
			for(MenuComponent mc:(List<MenuComponent>)m.getComponents()){
				tomenu(mc,menu,i++);
			}
		}
		return menu;
	}

	@Override
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		Map<String, Object> data = new HashMap<String, Object>();
		AppMenu entity = formBackingObject(request);
		entity.setBelongTo(belongTo);
		BindException errors = null;
		//手动建立上一级关系
		Integer parentId = RequestUtil.getInteger(request, "parentId");
		if(parentId!=null){
			entity.setParent(new AppMenu());
			entity.getParent().setMenuId(parentId);
		}
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 查看是否有相同的匹配字串
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				//保存，新的权限资源将被授权给超级管理员
				boolean isNew = isEntityNew(request);
				appMenuManager.saveFully(isNew,entity);
				if(isNew&&entity.getBelongTo().shortValue()==Constants.SECURITY_BELONGTO_ADMIN.shortValue()){
					data.put("message",getMessage("appMenu.default.grant", new Object[] {entity.getTitle(),Constants.DEFAULT_ADMIN_ROLE_NAME}));
				}
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}
		buildReturnInfo(data,entity,request);
		return getModelAndAjaxJsonView(data);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, AppMenu entity, BindException errors) {
		entity.setBelongTo(belongTo);
	}

}
